% sum q by q matrix by quintiles
function F = mysum(matrix, quintileflag, param)

    d = param.d;
    Q = param.Q;
    mysum1 = NaN(Q,d);
    for i = 1:d
       mysum1(:,i) = sum(matrix.*repmat(quintileflag(i,:),Q,1),2);  
    end   
    mysum2 = NaN(d,d);
    for i = 1:d
       mysum2(i,:) = sum(mysum1.*repmat(quintileflag(i,:)',1,d),1); 
    end
    F = mysum2;
    
end